package com.chexiehui.jc.ui.activity;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.aries.ui.view.radius.RadiusTextView;
import com.blankj.utilcode.util.StringUtils;
import com.chexiehui.jc.Constants;
import com.chexiehui.jc.R;
import com.chexiehui.jc.base.BaseModel;
import com.chexiehui.jc.base.BaseMvpActivity;
import com.chexiehui.jc.base.BasePage;
import com.chexiehui.jc.entity.UserInfo;
import com.chexiehui.jc.event.GlobalFollowUserEvent;
import com.chexiehui.jc.mvp.home.RecommendUserListCovenant;
import com.chexiehui.jc.mvp.home.RecommendUserListPresenter;
import com.chexiehui.jc.utils.BundleBuilder;
import com.chexiehui.jc.utils.GlideUtil;
import com.chexiehui.jc.utils.NoDoubleClickListener;
import com.chexiehui.jc.utils.NoDoubleClickUtils;
import com.chexiehui.jc.widget.LoadingLayout;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class RecommedUserListActivity extends BaseMvpActivity<RecommendUserListPresenter> implements RecommendUserListCovenant.View {

    @BindView(R.id.loadingLayout)
    LoadingLayout loadingLayout;
    @BindView(R.id.recycler)
    RecyclerView recycler;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    private CommonAdapter<UserInfo> listAdapter;
    private List<UserInfo> listData;
    private BasePage<UserInfo> page;

    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }

    @Override
    protected void setTitleBar() {
        titleBar.setTitleMainText("推荐用户");
    }

    @Override
    protected RecommendUserListPresenter createPresenter() {
        return new RecommendUserListPresenter(this);
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_recommend_user_list;
    }

    @Override
    protected void initView(Bundle var1) {
        loadingLayout.setStatus(LoadingLayout.Loading);
        refreshLayout.setEnableRefresh(true);
        refreshLayout.setEnableLoadMore(true);
        refreshLayout.setDisableContentWhenLoading(true);
        refreshLayout.setDisableContentWhenRefresh(true);
        refreshLayout.setEnableFooterFollowWhenLoadFinished(false);
        refreshLayout.setEnableLoadMoreWhenContentNotFull(false);
        refreshLayout.setEnableScrollContentWhenRefreshed(true);
        loadingLayout.setOnReloadListener(v -> {
            refreshLayout.finishRefresh(false);
            loadingLayout.setStatus(LoadingLayout.Loading);
            mvpPresenter.getList(1);
        });
        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                if (loadingLayout.getStatus() == LoadingLayout.Loading) {
                    refreshLayout.finishRefresh(false);
                    return;
                }
                mvpPresenter.getList(1);
            }

            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (page != null && page.getTotalRecordCount() > listData.size()) {
                    mvpPresenter.getList(page.getPageIndex() + 1);
                } else {
                    refreshLayout.finishLoadMoreWithNoMoreData();
                }
            }
        });
        recycler.setLayoutManager(new LinearLayoutManager(mContext));
        listData = new ArrayList<>();
        listAdapter = new CommonAdapter<UserInfo>(mContext, R.layout.item_home_slide_follow, listData) {
            @Override
            protected void convert(ViewHolder holder, UserInfo item, int position) {
                GlideUtil.loadImageViewCrop(mContext, item.getPhoto(), holder.getView(R.id.iv_item_avatar), R.drawable.shape_circle, R.drawable.shape_circle);
                holder.setText(R.id.tv_item_name, item.getName());
                holder.setText(R.id.tv_item_brief, item.getRemark());
                holder.setText(R.id.tv_item_follow, item.getFansCount() + "人关注");
                RadiusTextView rtv_item_follow_action = holder.getView(R.id.rtv_item_follow_action);
                if (item.getId().equals(getUserId())) {
                    rtv_item_follow_action.setVisibility(View.GONE);
                } else {
                    rtv_item_follow_action.setVisibility(View.VISIBLE);
                    rtv_item_follow_action.setSelected(item.isFollow());
                    rtv_item_follow_action.setText(item.isFollow() ? "取消关注" : "关注");
                    rtv_item_follow_action.setOnClickListener(new NoDoubleClickListener() {
                        @Override
                        public void onNoDoubleClick(View view) {
                            mvpPresenter.doFollowPerson(item.getId());
                        }
                    });
                }
            }
        };
        listAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                if (NoDoubleClickUtils.isDoubleClick()) return;
                startActivity(UserInfoActivity.class, new BundleBuilder()
                        .putString("userId", listAdapter.getDatas().get(position).getId())
                        .create());
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
        recycler.setAdapter(listAdapter);
        mvpPresenter.getList(1);
    }

    @Override
    public void onGetListSuccess(BaseModel<BasePage<UserInfo>> successResult) {
        page = successResult.getData();
        if (loadingLayout.getStatus() != LoadingLayout.Success) {
            loadingLayout.setStatus(LoadingLayout.Success);
        }
        if (refreshLayout.getState() == RefreshState.Refreshing) {
            refreshLayout.finishRefresh();
            listAdapter.getDatas().clear();
            listAdapter.getDatas().addAll(page.getItems());
            listAdapter.notifyDataSetChanged();
        } else if (refreshLayout.getState() == RefreshState.Loading) {
            listAdapter.getDatas().addAll(page.getItems());
            listAdapter.notifyDataSetChanged();
            if (page.getTotalRecordCount() <= listAdapter.getDatas().size()) {
                refreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                refreshLayout.finishLoadMore(true);
            }
        } else {
            refreshLayout.finishRefresh();
            listAdapter.getDatas().clear();
            listAdapter.getDatas().addAll(page.getItems());
            listAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onGetListFailure(BaseModel<Object> failureResult) {
        if (Constants.PAGE_DATA_EMPTY == failureResult.getResultCode()) {
            if (refreshLayout.getState() == RefreshState.Refreshing) {
                refreshLayout.finishRefresh(true);
                if (listAdapter.getDatas().size() > 0) {
                    listAdapter.getDatas().clear();
                    listAdapter.notifyDataSetChanged();
                }
                loadingLayout.setStatus(LoadingLayout.Empty);
                loadingLayout.setEmptyText(failureResult.getResultInfo());
            } else if (refreshLayout.getState() == RefreshState.Loading) {
                refreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                loadingLayout.setStatus(LoadingLayout.Empty);
                loadingLayout.setEmptyText(failureResult.getResultInfo());
            }
        } else {
            if (refreshLayout.getState() == RefreshState.Refreshing) {
                refreshLayout.finishRefresh(false);
            }
            if (refreshLayout.getState() == RefreshState.Loading) {
                refreshLayout.finishLoadMore(false);
            }
            if (listAdapter.getDatas().size() <= 0) {
                loadingLayout.setStatus(LoadingLayout.Error);
                loadingLayout.setErrorText(failureResult.getResultInfo());
            } else {
                showToast(failureResult.getResultInfo());
            }
        }
    }

    @Override
    public void onDoFollowPersonSuccess(BaseModel<String> successResult) {
        for (int i = 0; i < listAdapter.getDatas().size(); i++) {
            String id = listAdapter.getDatas().get(i).getId();
            if (id.equals(successResult.getData())) {
                EventBus.getDefault().post(new GlobalFollowUserEvent(successResult.getData(), !listAdapter.getDatas().get(i).isFollow()));
                break;
            }
        }
    }

    @Override
    public void onDoFollowPersonFailure(BaseModel<Object> failureResult) {
        showToast(failureResult.getResultInfo());
    }

    @Subscribe
    public void onGlobalFollowUserEvent(GlobalFollowUserEvent event) {
        if (event != null && !StringUtils.isTrimEmpty(event.getUserId())) {
            for (int i = 0; i < listAdapter.getDatas().size(); i++) {
                String id = listAdapter.getDatas().get(i).getId();
                if (id.equals(event.getUserId())) {
                    listAdapter.getDatas().get(i).setFollow(event.isFollow());
                    listAdapter.notifyItemChanged(i);
                }
            }
        }
    }
}
